<template>
  <BasicModal
    v-bind="$attrs"
    width="60%"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
  >
    <SubTableConfig
      ref="subTableRef"
      :sourceType="formConfig.currentItem!.dataSourceType"
      :client="formConfig.client"
    />

    <template #footer>
      <Spin :spinning="loading" :delay="200">
        <a-button @click="handleSubmit" type="primary">保存</a-button>
        <a-button @click="handleClose">取消</a-button>
      </Spin>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Spin } from 'ant-design-vue';
  import { useFormDesignState } from '../../../hooks/useFormDesignState';
  import SubTableConfig from '/@/views/config-center/model-design/components/sub-table/SubTableConfig.vue';
  import { SubTableInstance } from '/@/views/config-center/model-design/components/sub-table/subTable.data';

  export default defineComponent({
    name: 'SubTableConfigModal',
    components: { Spin, BasicModal, SubTableConfig },
    props: {
      isCustom: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['success', 'register'],
    setup() {
      const loading = ref(false);
      const { formConfig } = useFormDesignState();
      const subTableRef = ref<Nullable<SubTableInstance>>(null);

      const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner(
        async () => {
          subTableRef.value!.setValues(formConfig.value.currentItem!.simpleChildTable || {});
        },
      );

      const getTitle = computed(() => 'SQL配置');

      async function handleSubmit() {
        try {
          loading.value = true;
          changeLoading(true);
          setModalProps({ confirmLoading: true });
          const ret = await subTableRef.value!.getValues();
          formConfig.value.currentItem!.simpleChildTable = ret;
          handleClose();
        } finally {
          loading.value = false;
          changeLoading(false);
          setModalProps({ confirmLoading: false });
        }
      }

      async function handleClose() {
        closeModal();
      }
      return {
        loading,
        getTitle,
        registerModal,
        formConfig,
        subTableRef,
        handleSubmit,
        handleClose,
      };
    },
  });
</script>
